package com.example.controller;

import com.example.entity.FoodsRecipe;
import com.example.entity.User;
import com.example.service.FoodsRecipeService;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired  // 新增注入
    private FoodsRecipeService foodsRecipeService;
    // 用户列表（管理员权限）
    @GetMapping("/list")
    public String list(Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        List<User> users = userService.getAllUsers();
        model.addAttribute("users", users);
        return "user/list";
    }

    // 用户首页
    @GetMapping("/home")
    public String home(Model model, HttpSession session) {
        // 用户登录检查
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        // 加载用户数据
        model.addAttribute("user", user);

        // 新增：加载推荐食谱
        List<FoodsRecipe> recommendedRecipes = foodsRecipeService.getRecommendedRecipes();
        model.addAttribute("recommendedRecipes", recommendedRecipes);

        // 调试输出
        System.out.println("当前用户: " + user.getUsername());
        System.out.println("推荐食谱数量: " + recommendedRecipes.size());

        return "home";
    }

    // 添加用户页面（管理员权限）
    @GetMapping("/add")
    public String toAddPage(HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        return "user/add";
    }

    // 添加用户操作（管理员权限）
    @PostMapping("/add")
    public String add(User user, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        user.setRole(1);
        userService.addUser(user);
        return "redirect:/user/list";
    }

    // 编辑用户页面（管理员权限）
    @GetMapping("/edit/{userid}")
    public String toEditPage(@PathVariable("userid") Integer userid,
                             Model model, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        User user = userService.getUserById(userid);
        model.addAttribute("user", user);
        return "user/edit";
    }

    // 编辑用户操作（管理员权限）
    @PostMapping("/edit")
    public String edit(User user, HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        userService.updateUser(user);
        return "redirect:/user/list";
    }

    // 删除用户（管理员权限）
    @PostMapping("/delete/{userid}")
    public String delete(@PathVariable("userid") Integer userid,
                         HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null || currentUser.getRole() != 0) {
            return "redirect:/user/access-denied";
        }
        userService.deleteUser(userid);
        return "redirect:/user/list";
    }

    // 登录页面
    @GetMapping("/login")
    public String showLoginForm(HttpSession session, Model model,
                                @ModelAttribute("error") String error,
                                @ModelAttribute("success") String success) {
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return "redirect:/user/home";
        }

        if (error != null) {
            model.addAttribute("error", error);
        }
        if (success != null) {
            model.addAttribute("success", success);
        }

        return "login";
    }

    // 登录处理
    @PostMapping("/login")
    public String login(String username, String password,
                        HttpServletRequest request,
                        RedirectAttributes redirectAttributes) {
        User user = userService.getUserByNameAndPassword(username, password);

        if (user == null) {
            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
            return "redirect:/user/login";
        }

        HttpSession session = request.getSession();
        session.setAttribute("user", user);

        return user.getRole() == 0 ? "redirect:/user/list" : "redirect:/user/home";
    }

    // 注册页面
    @GetMapping("/register")
    public String showRegisterForm(Model model,
                                   @ModelAttribute("error") String error) {
        if (error != null) {
            model.addAttribute("error", error);
        }
        return "register";
    }

    // 注册处理 - 注册成功后跳转到登录页
    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           RedirectAttributes redirectAttributes) {

        if (userService.isUsernameExists(username)) {
            redirectAttributes.addFlashAttribute("error", "用户名已存在");
            return "redirect:/user/register";
        }

        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole(1);

        userService.addUser(newUser);

        redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
        return "redirect:/user/login";
    }

    // 访问拒绝页面
    @GetMapping("/access-denied")
    public String accessDenied() {
        return "access-denied";
    }

    // 退出登录功能
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login";
    }

}